<template>
  <el-dialog
    :title="
      mode === 'add'
        ? activeTreeNode
          ? '新增子类目'
          : '新增根类目'
        : '编辑类目'
    "
    :visible.sync="dialogVisible"
    width="50%"
    :before-close="closeDialog"
  >
    <div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="130px"
        size="small"
      >
        <el-form-item
          v-if="mode === 'edit' && activeTreeNode && activeTreeNode.level !== 1"
          label="上级类目："
          >{{ activeTreeNode.parentTitle }}
        </el-form-item>
        <el-form-item v-if="mode === 'add' && activeTreeNode" label="上级类目："
          >{{ activeTreeNode.title }}
        </el-form-item>
        <el-form-item label="类别名称：" prop="title">
          <el-input
            v-model.trim="form.title"
            class="w-300-h-32"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="类别编码：">
          <el-input
            v-model="form.categoryNo"
            class="w-300-h-32"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="类目商品属性：" prop="specList">
          <el-card
            v-for="(item, index) in form.specList"
            :key="'spec-' + index"
            class="spec-card"
          >
            <div slot="header" class="clearfix">
              <span>{{ item.title }}</span>
              <el-button
                style="float: right"
                type="text"
                @click="delSpec(index)"
                >删除
              </el-button>
            </div>
            <el-form-item
              :prop="'specList.' + index + '.attrList'"
              :rules="rules.attrList"
            >
              <el-tag
                v-for="(tagItem, tagIndex) in item.attrList"
                :key="'attr-' + tagIndex"
                :disable-transitions="false"
                closable
                @close="closeAttr(item.attrList, tagIndex)"
                >{{ tagItem.title }}
              </el-tag>
              <div>
                <el-input
                  v-if="item.inputVisible"
                  ref="saveAttrInput"
                  v-model="item.inputValue"
                  class="w-450-h-32"
                  size="small"
                  placeholder="请输入属性选项"
                  maxlength="30"
                  show-word-limit
                  @keyup.enter.native="addAttr(item)"
                  @blur="addAttr(item)"
                />
                <el-button
                  v-else
                  size="small"
                  style="height: 32px"
                  @click="showAttrInput(item)"
                  >+ 增加类目属性选项
                </el-button>
              </div>
            </el-form-item>
          </el-card>

          <el-input
            v-if="specInputVisible"
            ref="saveSpecInput"
            v-model.trim="form.specInputValue"
            class="w-300-h-32"
            size="small"
            placeholder="请输入属性名"
            maxlength="10"
            show-word-limit
            @keyup.enter.native="addSpec"
            @blur="addSpec"
          />

          <el-button
            v-else
            type="text"
            icon="el-icon-plus"
            style="height: 32px"
            @click="showSpecInput"
            >增加类目商品属性
          </el-button>
        </el-form-item>
        <el-form-item label="类目商品参数：">
          <el-card v-if="form.paramList.length > 0" class="spec-card">
            <el-tag
              v-for="(paramItem, paramIndex) in form.paramList"
              :key="'param-' + paramIndex"
              :disable-transitions="false"
              closable
              @close="closeParam(paramIndex)"
              >{{ paramItem }}
            </el-tag>
            <div>
              <el-input
                v-if="paramInputVisible"
                ref="saveParamInput"
                v-model.trim="form.paramInputValue"
                class="w-300-h-32"
                size="small"
                placeholder="请输入参数"
                maxlength="10"
                show-word-limit
                @keyup.enter.native="addParams"
                @blur="addParams"
              />
              <el-button
                v-else
                size="small"
                style="height: 32px"
                @click="showParamInput"
                >+ 增加类目商品参数
              </el-button>
            </div>
          </el-card>

          <div v-else>
            <el-input
              v-if="paramInputVisible"
              ref="saveParamInput"
              v-model.trim="form.paramInputValue"
              class="w-300-h-32"
              size="small"
              placeholder="请输入参数"
              maxlength="10"
              show-word-limit
              @keyup.enter.native="addParams"
              @blur="addParams"
            />
            <el-button
              v-else
              type="text"
              icon="el-icon-plus"
              style="height: 32px"
              @click="showParamInput"
              >增加类目商品参数
            </el-button>
          </div>
        </el-form-item>
        <!-- <el-form-item>
            <el-button type="primary" round @click="submit">保 存</el-button>
            <el-button
              v-show="mode === 'edit'"
              round
              @click="reset"
            >重 置
            </el-button>
            <el-button
              v-show="mode === 'edit'"
              round
              @click="del"
            >删 除
            </el-button>
          </el-form-item> -->
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog()">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  categoryDetail,
  categoryTree,
  addCategory,
  delCategory,
  updateCategory,
  getSpecId,
  getAttrId,
} from "@/views/wxaMallModule/api/category";
export default {
  data() {
    return {
      rules: {
        title: [{ required: true, message: "请输入类别名称", trigger: "blur" }],
        categoryNo: [
          { required: true, message: "请输入类别编码", trigger: "blur" },
        ],
        attrList: [
          {
            type: "array",
            required: true,
            message: "请至少设置一种属性选项",
            // trigger: "change",
          },
        ],
      },
      dialogVisible: false,
      specInputVisible: false,
      paramInputVisible: false,
      mode: "",
      form: {
        categoryNo: "",
        icon: "",
        parentId: 0,
        parentIds: "",
        ranking: "",
        paramList: [],
        specList: [],
        title: "",
        specInputValue: "",
        paramInputValue: "",
      },
      activeTreeNode: "",
    };
  },
  methods: {
    handleClose() {},
    openDialog(data) {
      data ? (this.activeTreeNode = data) : "";
      if (data?.type == "add") {
        this.form.parentId = data.id;
      }
      // console.log(this.activeTreeNode);
      this.mode = !data || data.type == "add" ? "add" : "edit";
      data && this.mode == "edit" && this.getDetail(data.id);
      this.dialogVisible = true;
    },
    getDetail(id) {
      console.log(id);
      categoryDetail({ categoryId: id })
        .then((res) => {
          res.data.specList.map((v) => {
            v.inputVisible = false;
            v.inputValue = "";
          });
          this.form = res.data;
          this.$nextTick(() => {
            this.$refs.form.clearValidate();
          });
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false;
        });
    },
    // 新增attr
    addAttr(row) {
      const inputValue = row.inputValue;
      if (inputValue) {
        const flag = row.attrList.some((v) => {
          if (inputValue === v.title) {
            return true;
          }
        });
        if (flag) {
          row.inputVisible = false;
          row.inputValue = "";
          return;
        }
        getAttrId({ specId: row.id, title: inputValue })
          .then((res) => {
            row.attrList.push({
              title: inputValue,
              id: res.data,
            });
            // row.inputVisible = false;
            row.inputValue = "";
          })
          .catch((err) => {})
          .finally(() => {});
      } else {
        row.inputVisible = false;
        row.inputValue = "";
      }
    },
    closeAttr(row, index) {
      row.splice(index, 1);
    },
    // 新增商品参数
    addParams() {
      const inputValue = this.form.paramInputValue;
      if (inputValue) {
        this.form.paramList.push(inputValue);
        this.form.paramList = [...new Set(this.form.paramList)];
        this.form.paramInputValue = "";
      } else {
        this.paramInputVisible = false;
        this.form.paramInputValue = "";
      }
    },
    // 显示specInput
    showSpecInput() {
      this.specInputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveSpecInput.$refs.input.focus();
      });
    },
    // 删除spec
    delSpec(index) {
      this.form.specList.splice(index, 1);
    },
    // 显示attrInput
    showParamInput() {
      this.paramInputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveParamInput.$refs.input.focus();
      });
    },
    // 新增spec
    addSpec() {
      const inputValue = this.form.specInputValue;
      if (inputValue) {
        const flag = this.form.specList.some((v) => {
          if (inputValue === v.title) {
            return true;
          }
        });
        if (flag) {
          this.specInputVisible = false;
          this.form.specInputValue = "";
          return;
        }
        getSpecId({ title: inputValue })
          .then((res) => {
            this.form.specList.push({
              title: inputValue,
              id: res.data,
              attrList: [],
              inputVisible: false,
              inputValue: "",
            });
            this.specInputVisible = false;
            this.form.specInputValue = "";
          })
          .catch((err) => {})
          .finally(() => {});
      } else {
        this.specInputVisible = false;
        this.form.specInputValue = "";
      }
    },
    // 关闭参数
    closeParam(index) {
      this.form.paramList.splice(index, 1);
    },
    // 显示attrInput
    showAttrInput(item) {
      // 其它移除
      this.form.specList.forEach((v) => {
        if (v.id != item.id) {
          v.inputVisible = false;
        }
      });
      // 当前激活
      item.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveAttrInput[0].$refs.input.focus();
      });
    },
    // 保存
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.form.id) {
            updateCategory(this.form)
              .then((res) => {
                this.$notify({
                  title: "成功",
                  message: "更新成功",
                  type: "success",
                  duration: 2000,
                  offset: 40,
                });
                this.$emit("upData");
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            addCategory(this.form)
              .then((res) => {
                this.$notify({
                  title: "成功",
                  message: "新增成功",
                  type: "success",
                  duration: 2000,
                  offset: 40,
                });
                // 清空数据
                this.form = {
                  categoryNo: "",
                  icon: "",
                  parentId: this.form.parentId,
                  parentIds: this.form.parentIds,
                  ranking: "",
                  paramList: [],
                  specList: [],
                  title: "",
                  specInputValue: "",
                  paramInputValue: "",
                };
                this.$emit("upData");
              })
              .finally(() => {
                this.loading = false;
              });
          }
          this.dialogVisible = false;
        }
      });
    },
    closeDialog() {
      this.dialogVisible = false;
      this.activeTreeNode = "";
      this.form = {
        categoryNo: "",
        icon: "",
        parentId: 0,
        parentIds: "",
        ranking: "",
        paramList: [],
        specList: [],
        title: "",
        specInputValue: "",
        paramInputValue: "",
      };
      // done()
      // this.form.
    },
  },
};
</script>

<style>
</style>